package com.cj.web.before;

import com.cj.entity.User;
import com.cj.service.UserService;
import com.cj.utils.JSONUtils;
import com.cj.utils.ResultVO;
import com.cj.web.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: chenjie
 * @Date: 2021/7/13 - 07 - 13 - 13:49
 * @Description: com.cj.web.before
 */
@WebServlet("/userWeb")
public class UserServlet extends BaseServlet {
    ResultVO vo;
    UserService service = new UserService();
    public void checkPhone(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String phone = req.getParameter("phone");

        User user = service.checkPhone(phone);

        if(user !=null){
            vo = new ResultVO(500,"手机号已存在",null);
        }else{
            vo = new ResultVO(200,"手机号可以使用",null);
        }
        JSONUtils.objToJson(vo,resp);
    }


    public void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");

        User user = new User();
        user.setName(name);
        user.setPassword(password);
        user.setPhone(phone);

        int row = service.insertUser(user);

        if(row>0){
            vo = new ResultVO(200,"注册成功",null);
        }else{
            vo = new ResultVO(500,"注册失败",null);
        }
        JSONUtils.objToJson(vo,resp);
    }


//    登录
    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");


        User user = service.loginWeb(phone,password);

        if(user !=null){
//            返回 user 。。 客户端用 sessionStroage 把user存起来。。关闭浏览器消失
            vo = new ResultVO(200,"登录成功",user);
        }else{
            vo = new ResultVO(500,"登录失败",null);
        }
        JSONUtils.objToJson(vo,resp);
    }
}
